package com.lanp.gencode.apifox;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lanp.gencode.utils.DocUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class run {


    static String
            reqBean = "ChainCompanySaveBo",
            resBean = "EmptyCC",
            Method = "POST",
            ApiName = "添加连锁商品",
            ApiPath = "{{bff-main}}/chain/product/v1/add";
    static boolean
            isSigoResult = true,
            isResPage = false;


    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {

        List<Properties> res = new ArrayList<>();

        List<DocUtil.VoDoc> resVoDoc = getVoDoc(resBean);

        for (DocUtil.VoDoc voDoc : resVoDoc) {
            if (StringUtils.equalsAny(voDoc.getFieldName(), "serialVersionUID", "available")) {
                continue;
            }
            String fieldType = voDoc.getFieldType();
            if (fieldType.equals("List")) {
                res.add(handleList(voDoc));
            } else {
                res.add(new Properties(
                        voDoc.getFieldName(),
                        toApiType(voDoc.getFieldType()),
                        voDoc.getCommentText()));
            }
        }

        Api api = new Api();
        api.setMethod(Method);
        api.setName(ApiName);
        api.setResPage(isSigoResult);
        api.setResPage(isResPage);
        api.setPath(ApiPath);
        //res.add(new Properties("company_id", "int", "店铺id"));
        //res.add(new Properties("company_name", "string", "店铺名称"));
        //ArrayProperties cityList = new ArrayProperties("cityList", "array", "城市列表");
        //cityList.addProperties(new Properties("city_code", "string", "城市code"));
        //cityList.addProperties(new Properties("city_name", "string", "城市名称"));
        //res.add(cityList);

        api.setResponses(res);
        api.setResponseExamples("{\n    \"code\": 200,\n    \"data\": {\n        \"page_data\": [\n            {\n                \"available\": true,\n                \"base_price\": 6,\n                \"create_company_id\": 196283495129984,\n                \"create_time\": 1682414369525,\n                \"create_user\": \"zj\",\n                \"del_time\": 0,\n                \"del_user\": \"\",\n                \"goods_weight_limit\": 10,\n                \"local_freight_rule_id\": 1105623224312843,\n                \"mod_time\": 1682414369525,\n                \"mod_user\": \"zj\",\n                \"rule_item_list\": [\n                    {\n                        \"available\": true,\n                        \"every_price\": 2,\n                        \"item_type\": 1,\n                        \"local_freight_rule_id\": 1105623224312843,\n                        \"rule_item_id\": 1105623224312844,\n                        \"satisfy\": 5\n                    }\n                ],\n                \"rule_name\": \"同城配送A\"\n            }\n        ],\n        \"page_num\": 1,\n        \"page_size\": 10,\n        \"total_count\": 1\n    },\n    \"message\": null\n}");
        List<Properties> req = new ArrayList<>();

        List<DocUtil.VoDoc> reqVoDoc = getVoDoc(reqBean);

        for (DocUtil.VoDoc voDoc : reqVoDoc) {
            if (StringUtils.equalsAny(voDoc.getFieldName(), "serialVersionUID", "available")) {
                continue;
            }
            String fieldType = voDoc.getFieldType();
            if (fieldType.equals("List")) {
                req.add(handleList(voDoc));
            } else {
                req.add(new Properties(
                        voDoc.getFieldName(),
                        toApiType(voDoc.getFieldType()),
                        voDoc.getCommentText()));
            }
        }


        api.setRequestBody(req);


        JSONObject resJson_properties = new JSONObject();
        if (api.isSigoResult()) {
            resJson_properties.put("code", new HashMap<String, String>() {{
                put("type", "integer");
            }});
            resJson_properties.put("message", new HashMap<String, String>() {{
                put("type", "null");
            }});
            Map<String, Object> fieldMap = new HashMap<>();
            if (api.isResPage()) {
                fieldMap.put("page_num", new Properties("integer", "页码"));
                fieldMap.put("page_size", new Properties("integer", "每页数量"));
                fieldMap.put("total_count", new Properties("integer", "总数"));
                fieldMap.put("page_data", new HashMap<String, Object>() {{
                    put("type", "array");
                    put("items", new HashMap<String, Object>() {{
                        put("type", "object");
                        put("properties", api.toResMap());
                    }});
                }});
            } else {
                Map<String, Properties> resMap = api.toResMap();
                for (Map.Entry<String, Properties> entry : resMap.entrySet()) {
                    fieldMap.put(entry.getKey(), entry.getValue());
                }
            }
            resJson_properties.put("data", new HashMap<String, Object>() {{
                put("type", "object");
                put("properties", fieldMap);
            }});
        }


        JSONObject resJson_jsonSchema = new JSONObject();
        resJson_jsonSchema.put("type", "object");
        resJson_jsonSchema.put("properties", resJson_properties);
        JSONObject resJson = new JSONObject();
        resJson.put("name", "成功");
        resJson.put("code", 200);
        resJson.put("contentType", "json");
        resJson.put("jsonSchema", resJson_jsonSchema);


        JSONObject reqJson_jsonSchema = new JSONObject();
        reqJson_jsonSchema.put("type", "object");
        reqJson_jsonSchema.put("properties", api.toReqMap());
        JSONObject reqJson = new JSONObject();
        reqJson.put("type", "application/json");
        reqJson.put("jsonSchema", reqJson_jsonSchema);


        JSONObject responseExamplesJson = new JSONObject();
        responseExamplesJson.put("name", "成功示例");
        responseExamplesJson.put("data", "{\n    \"code\": 200,\n    \"data\": {\n        \"page_data\": [\n            {\n                \"available\": true,\n                \"base_price\": 6,\n                \"create_company_id\": 196283495129984,\n                \"create_time\": 1682414369525,\n                \"create_user\": \"zj\",\n                \"del_time\": 0,\n                \"del_user\": \"\",\n                \"goods_weight_limit\": 10,\n                \"local_freight_rule_id\": 1105623224312843,\n                \"mod_time\": 1682414369525,\n                \"mod_user\": \"zj\",\n                \"rule_item_list\": [\n                    {\n                        \"available\": true,\n                        \"every_price\": 2,\n                        \"item_type\": 1,\n                        \"local_freight_rule_id\": 1105623224312843,\n                        \"rule_item_id\": 1105623224312844,\n                        \"satisfy\": 5\n                    }\n                ],\n                \"rule_name\": \"同城配送A\"\n            }\n        ],\n        \"page_num\": 1,\n        \"page_size\": 10,\n        \"total_count\": 1\n    },\n    \"message\": null\n}");


        example = example.replace("#responses#", resJson.toJSONString());
        example = example.replace("#responseExamples#", responseExamplesJson.toJSONString());
        example = example.replace("#requestBody#", reqJson.toJSONString());
        example = example.replace("#name#", api.getName());
        example = example.replace("#method#", api.getMethod());
        example = example.replace("#path#", api.getPath());

        all = all.replace("#items#", example);
        System.out.println(all);

        //写入文件
        File file = new File("C:\\Users\\jiangpeng\\Desktop\\aa.json");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(all.getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();
    }



    static List<DocUtil.VoDoc> getVoDoc(String java) {
        if(StringUtils.isBlank(java)){
            return new ArrayList<>();
        }
        List<DocUtil.VoDoc> voDocs = DocUtil.JavaToDoc(
                "E:\\code\\jp\\code-test\\src\\main\\java\\com\\lanp\\gencode\\apifox\\model\\"
                        + java
                        + ".java");
        return voDocs;
    }

    static ArrayProperties handleList(DocUtil.VoDoc lvDoc) {
        ArrayProperties ress = new ArrayProperties(lvDoc.getFieldName(), lvDoc.getFieldType(), lvDoc.getCommentText());
        if (StringUtils.equalsAny(lvDoc.getTclass(), "Long", "Integer", "String", "Short", "Long", "Long")) {
            ress.items.put("type", toApiType(lvDoc.getTclass()));
            return ress;
        }
        List<DocUtil.VoDoc> listDoc = getVoDoc(lvDoc.getTclass());
        for (DocUtil.VoDoc voDoc : listDoc) {
            if (StringUtils.equalsAny(voDoc.getFieldName(), "serialVersionUID", "available"
                    ,"del_time","del_user")) {
                continue;
            }
            String fieldType = voDoc.getFieldType();
            if (fieldType.equals("List")) {
                ArrayProperties arrayProperties = handleList(voDoc);
                ress.addProperties(arrayProperties);
            } else {
                ress.addProperties(new Properties(
                        voDoc.getFieldName(),
                        toApiType(voDoc.getFieldType()),
                        voDoc.getCommentText()));
            }
        }
        return ress;
    }

    static String toApiType(String javaType) {
        switch (javaType) {
            case "int":
            case "long":
            case "Long":
            case "Short":
            case "short":
            case "integer":
                return "integer";
            case "list":
            case "List":
                return "array";
            case "Map":
            case "HashMap":
                return "object";
            case "boolean":
            case "Boolean":
                return "boolean";
            case "String":
                return "string";
            case "BigDecimal":
            case "Double":
            case "double":
                return "number";
            case "Date":
                return "integer";
            default:
                return javaType;
        }
    }


    static String example = "{\n" +
            "  \"name\": \"#name#\",\n" +
            "  \"api\": {\n" +
            "    \"id\": \"\",\n" +
            "    \"method\": \"#method#\",\n" +
            "    \"path\": \"#path#\",\n" +
            "    \"parameters\": {\n" +
            "      \"path\": [],\n" +
            "      \"header\": [\n" +
            "        {\n" +
            "          \"required\": true,\n" +
            "          \"description\": \"\",\n" +
            "          \"type\": \"string\",\n" +
            "          \"name\": \"token\",\n" +
            "          \"id\": \"\",\n" +
            "          \"example\": \"eyJhbGciOiJIUzI1NiJ9.eyJzaG9wX2lkIjoiMTk2MjgzNDk1MTI5OTg0IiwiYWNjb3VudF9pZCI6IjE5NjI4MzUwMzUxODU5MyIsInVzZXJfaWQiOiIxMjEwODAxMTkzMTU4NDAiLCJpc3MiOiJhdXRoLWNlbnRlciIsImlhdCI6MTY4MjI0MjI3Nn0.L2GVRyJWHcIos43jhi6tYBazyQSr3xVUCbyiPPCd5fQ\",\n" +
            "          \"enable\": true\n" +
            "        }\n" +
            "      ]\n" +
            "    },\n" +
            "    \"auth\": {},\n" +
            "    \"commonParameters\": {\n" +
            "      \"query\": [],\n" +
            "      \"body\": [],\n" +
            "      \"cookie\": [],\n" +
            "      \"header\": []\n" +
            "    },\n" +
            "    \"responses\": [#responses#],\n" +
            "    \"responseExamples\": [#responseExamples#],\n" +
            "    \"requestBody\": #requestBody#,\n" +
            "    \"description\": \"\",\n" +
            "    \"tags\": [],\n" +
            "    \"status\": \"developing\",\n" +
            "    \"serverId\": \"\",\n" +
            "    \"operationId\": \"\",\n" +
            "    \"sourceUrl\": \"\",\n" +
            "    \"ordering\": 17,\n" +
            "    \"cases\": [\n" +
            "      {\n" +
            "        \"id\": 3501541,\n" +
            "        \"type\": \"http\",\n" +
            "        \"path\": null,\n" +
            "        \"name\": \"成功\",\n" +
            "        \"responseId\": \"\",\n" +
            "        \"parameters\": {\n" +
            "          \"query\": [],\n" +
            "          \"path\": [],\n" +
            "          \"cookie\": [],\n" +
            "          \"header\": [\n" +
            "            {\n" +
            "              \"id\": \"4GrwdtF7K8\",\n" +
            "              \"relatedId\": \"Ul4Vh1SJEm\",\n" +
            "              \"relatedName\": \"token\",\n" +
            "              \"value\": \"eyJhbGciOiJIUzI1NiJ9.eyJzaG9wX2lkIjoiMTEyMzc1MzEzNzAwMzEzNiIsImFjY291bnRfaWQiOiIxMTIzNzUzMTM3MDAzMTM3IiwidXNlcl9pZCI6IjEyMTA4NTE1MjQ4MDY0MCIsImlzcyI6ImF1dGgtY2VudGVyIiwiaWF0IjoxNzAyODgzNjQ5fQ.82ybowyt7SZgqTGgtOP2rsJ-DSJVlAiMevRtwZEAydU\",\n" +
            "              \"enable\": true,\n" +
            "              \"isDelete\": false\n" +
            "            }\n" +
            "          ]\n" +
            "        },\n" +
            "        \"commonParameters\": {\n" +
            "          \"query\": [],\n" +
            "          \"body\": [],\n" +
            "          \"header\": [],\n" +
            "          \"cookie\": []\n" +
            "        },\n" +
            "        \"requestBody\": {\n" +
            "          \"parameters\": [],\n" +
            "          \"data\": \"{\\r\\n    \\\"page_flag\\\": true\\r\\n}\",\n" +
            "          \"generateMode\": \"normal\"\n" +
            "        },\n" +
            "        \"auth\": {},\n" +
            "        \"advancedSettings\": {\n" +
            "          \"isDefaultUrlEncoding\": 1\n" +
            "        },\n" +
            "        \"preProcessors\": [],\n" +
            "        \"postProcessors\": [],\n" +
            "        \"inheritPostProcessors\": {},\n" +
            "        \"inheritPreProcessors\": {}\n" +
            "      }\n" +
            "    ],\n" +
            "    \"mocks\": [],\n" +
            "    \"customApiFields\": \"\",\n" +
            "    \"advancedSettings\": {},\n" +
            "    \"mockScript\": {},\n" +
            "    \"codeSamples\": [],\n" +
            "    \"commonResponseStatus\": {},\n" +
            "    \"responseChildren\": [],\n" +
            "    \"preProcessors\": [],\n" +
            "    \"postProcessors\": [],\n" +
            "    \"inheritPostProcessors\": {},\n" +
            "    \"inheritPreProcessors\": {}\n" +
            "  }\n" +
            "}";


    static String all = "{\n" +
            "  \"apifoxProject\": \"1.0.0\",\n" +
            "  \"$schema\": {\n" +
            "    \"app\": \"apifox\",\n" +
            "    \"type\": \"project\",\n" +
            "    \"version\": \"1.2.0\"\n" +
            "  },\n" +
            "  \"info\": {\n" +
            "    \"name\": \"眼镜圈平台API\",\n" +
            "    \"description\": \"\",\n" +
            "    \"mockRule\": {}\n" +
            "  },\n" +
            "  \"apiCollection\": [\n" +
            "    {\n" +
            "      \"name\": \"根目录\",\n" +
            "      \"auth\": {},\n" +
            "      \"parentId\": 0,\n" +
            "      \"serverId\": \"\",\n" +
            "      \"description\": \"\",\n" +
            "      \"identityPattern\": {\n" +
            "        \"httpApi\": {\n" +
            "          \"type\": \"methodAndPath\",\n" +
            "          \"bodyType\": \"\",\n" +
            "          \"fields\": []\n" +
            "        }\n" +
            "      },\n" +
            "      \"preProcessors\": [\n" +
            "        {\n" +
            "          \"id\": \"inheritProcessors\",\n" +
            "          \"type\": \"inheritProcessors\",\n" +
            "          \"data\": {}\n" +
            "        }\n" +
            "      ],\n" +
            "      \"postProcessors\": [\n" +
            "        {\n" +
            "          \"id\": \"inheritProcessors\",\n" +
            "          \"type\": \"inheritProcessors\",\n" +
            "          \"data\": {}\n" +
            "        }\n" +
            "      ],\n" +
            "      \"inheritPostProcessors\": {},\n" +
            "      \"inheritPreProcessors\": {},\n" +
            "      \"items\": [\n" +
            "        #items#\n" +
            "      ]\n" +
            "    }\n" +
            "  ],\n" +
            "  \"socketCollection\": [],\n" +
            "  \"docCollection\": [],\n" +
            "  \"schemaCollection\": [],\n" +
            "  \"responseCollection\": [],\n" +
            "  \"commonScripts\": [\n" +
            "    {\n" +
            "      \"name\": \"密码加密\",\n" +
            "      \"description\": \"\",\n" +
            "      \"content\": \"pm.sendRequest(pm.environment.get('BASE_URL') + \\\"/rsaPublickey\\\", function (err, response) {\\r\\n    var publicKey = response.json().data;\\r\\n    console.log(publicKey);\\r\\n\\r\\n    var paramJson = JSON.parse(pm.request.body.raw)\\r\\n    console.log(paramJson)\\r\\n    var password2 = paramJson.password2\\r\\n\\r\\n    var encryptPwd = encrypt(password2, publicKey)\\r\\n    console.log(paramJson)\\r\\n    pm.environment.set(\\\"password\\\", encryptPwd);\\r\\n});\\r\\n\\r\\n// 加密\\r\\nfunction encrypt(encryptData, pubk) {\\r\\n    var jsrsasign = require(\\\"jsrsasign\\\");\\r\\n    pubk = \\\"-----BEGIN PUBLIC KEY-----\\\" + pubk + \\\"-----END PUBLIC KEY-----\\\";\\r\\n    // 读取解析pem格式的秘钥, 生成秘钥实例 (RSAKey) \\r\\n    var pub = jsrsasign.KEYUTIL.getKey(pubk);\\r\\n    var enc = jsrsasign.KJUR.crypto.Cipher.encrypt(encryptData, pub);\\r\\n    // console.log(\\\"jsrsasign decrypt: \\\" + enc);\\r\\n    // console.log(\\\"jsrsasign hextob64: \\\" + jsrsasign.hextob64(enc));\\r\\n    return jsrsasign.hextob64(enc);\\r\\n}\",\n" +
            "      \"runMode\": \"independent\",\n" +
            "      \"stickyOrdering\": 0,\n" +
            "      \"ordering\": 10,\n" +
            "      \"id\": \"345051\"\n" +
            "    }\n" +
            "  ],\n" +
            "  \"globalVariables\": [],\n" +
            "  \"commonParameters\": null,\n" +
            "  \"projectSetting\": {\n" +
            "    \"id\": \"326149\",\n" +
            "    \"auth\": {},\n" +
            "    \"servers\": [\n" +
            "      {\n" +
            "        \"name\": \"dm-api\",\n" +
            "        \"id\": \"de07fa66-63f8-411c-85c6-1ddc7ac8e097\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"name\": \"默认服务\",\n" +
            "        \"id\": \"default\"\n" +
            "      }\n" +
            "    ],\n" +
            "    \"gateway\": [],\n" +
            "    \"language\": \"zh-CN\",\n" +
            "    \"apiStatuses\": [\n" +
            "      \"developing\",\n" +
            "      \"testing\",\n" +
            "      \"released\",\n" +
            "      \"deprecated\"\n" +
            "    ],\n" +
            "    \"mockSettings\": {},\n" +
            "    \"preProcessors\": [],\n" +
            "    \"postProcessors\": [],\n" +
            "    \"advancedSettings\": {},\n" +
            "    \"initialDisabledMockIds\": [],\n" +
            "    \"cloudMock\": {\n" +
            "      \"security\": \"free\",\n" +
            "      \"enable\": false,\n" +
            "      \"tokenKey\": \"apifoxToken\"\n" +
            "    }\n" +
            "  }\n" +
            "}";
}
